<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\model\Goods;
use app\common\model\GoodsCategory;
use app\common\model\GoodsContentManager;
use app\common\model\GoodsSpecRelation;
use app\common\model\GoodsTag;
use app\common\model\GoodsTagRelation;
use think\facade\Db;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use support\Request;
use support\Response;

/**
 * 火车头发布接口
 * 用于火车头软件发布商品内容
 */
class HuoChePublish
{
    /**
     * API密钥，用于验证请求合法性
     * @var string
     */
    private $api_key = 'huoche_api_key_2024';

    /**
     * 允许上传的图片扩展名
     * @var array
     */
    private $allowed_exts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

    /**
     * 日志实例
     * @var Logger
     */
    private $logger;

    /**
     * 构造函数
     */
    public function __construct()
    {
        // 初始化日志
        $this->logger = new Logger('huoche_publish');
        $this->logger->pushHandler(new StreamHandler(runtime_path() . '/logs/huoche_publish.log', Logger::INFO));
    }

    /**
     * 获取API密钥
     * @return string
     */
    private function getApiKey()
    {
        return $this->api_key;
    }

    /**
     * 获取允许的扩展名
     * @return array
     */
    private function getAllowedExts()
    {
        return $this->allowed_exts;
    }

    /**
     * 发布商品接口
     * @param Request $request
     * @return Response
     */
    public function publish(Request $request)
    {
        try {
            // 验证API密钥
            $api_key = $request->get('api_key', '');
            if ($api_key !== $this->getApiKey()) {
                return json(['code' => 0, 'msg' => 'API密钥错误']);
            }

            // 获取参数
            $name                 = $request->post('name', ''); // 商品名称
            $category_name        = $request->post('category_name', ''); // 分类名称
            $cate_id              = (int) $request->post('cate_id', 0); // 分类ID（可选）
            $auto_create_category = (bool) $request->post('auto_create_category', false); // 是否自动创建分类
            $price                = (float) $request->post('price', 0); // 价格
            $cost_price           = (float) $request->post('cost_price', 0); // 成本价
            $content              = $request->post('content', ''); // 商品详情
            $paid_content         = $request->post('paid_content', ''); // 付费内容
            $paid_content_type    = $request->post('paid_content_type', 'text'); // 付费内容类型
            $tags                 = $request->post('tags', ''); // 标签，多个用逗号分隔
            $sort                 = (int) $request->post('sort', 0); // 排序
            $status               = (int) $request->post('status', 1); // 状态：1-上架，0-下架
            $seo_title            = $request->post('seo_title', ''); // SEO标题
            $seo_keywords         = $request->post('seo_keywords', ''); // SEO关键词
            $seo_description      = $request->post('seo_description', ''); // SEO描述
            $template             = $request->post('template', ''); // 模板

            // spec

            // 作者
            $author = $request->post('author', ''); // 作者

            // 上传图片
            $slider_images = [];
            $images        = $request->post('images');
            // 以，分割并合并到slider_images
            $images        = explode(',', $images);
            $slider_images = array_map(function ($item) {
                return trim($item);
            }, $images);

            // 参数验证
            if (empty($name)) {
                return json(['code' => 0, 'msg' => '商品名称不能为空']);
            }

            if (empty($content)) {
                return json(['code' => 0, 'msg' => '商品详情不能为空']);
            }

            // 处理分类
            // 如果提供了分类名称，则通过名称查找分类ID
            if (!empty($category_name)) {
                $category = GoodsCategory::where('name', $category_name)->find();
                if ($category) {
                    $cate_id = $category->getData('id');
                    $this->logger->info('通过分类名称找到分类', ['name' => $category_name, 'id' => $cate_id]);
                } elseif ($auto_create_category) {
                    // 如果分类不存在且允许自动创建，则创建新分类
                    $category = new GoodsCategory();
                    $maxSort  = GoodsCategory::max('sort');
                    $maxSort  = $maxSort ? $maxSort + 1 : 1;

                    $categoryData = [
                        'name'    => $category_name,
                        'pid'     => 0, // 默认为顶级分类
                        'sort'    => $maxSort,
                        'status'  => 1,
                        'is_menu' => 1,
                        'spac_id' => 1,
                    ];

                    $category->save($categoryData);
                    $cate_id = $category->getData('id');
                    $this->logger->info('自动创建分类成功', ['name' => $category_name, 'id' => $cate_id]);
                } else {
                    return json(['code' => 0, 'msg' => '分类不存在: ' . $category_name]);
                }
            }

            // 验证最终分类ID
            if (empty($cate_id)) {
                return json(['code' => 0, 'msg' => '商品分类不能为空，请提供分类ID或有效的分类名称']);
            }

            // 验证分类是否存在
            $category = GoodsCategory::find($cate_id);
            if (!$category) {
                return json(['code' => 0, 'msg' => '商品分类不存在']);
            }

            // 开始事务
            Db::startTrans();

            try {
                // 创建商品
                $good = new Goods();
                // 获取最大排序值
                $maxSort = 0;
                if (!$sort) {
                    $maxSort = Goods::max('sort');
                    $maxSort = $maxSort ? $maxSort + 1 : 1;
                }

                $goodData = [
                    'name'            => $name,
                    'cate_id'         => $cate_id,
                    'price'           => $price,
                    'cost_price'      => $cost_price,
                    'content'         => $content,
                    'slider_image'    => $slider_images,
                    'sort'            => $sort ?: $maxSort,
                    'status'          => $status,
                    'seo_title'       => $seo_title ?: $name,
                    'seo_keywords'    => $seo_keywords,
                    'seo_description' => $seo_description,
                    'template'        => $template,
                    'views'           => 0,
                    'sales_volume'    => 0,
                    'comments_count'  => 0
                ];
                $good->save($goodData);

                // 保存付费内容
                $goodId         = $good->getData('id');
                $contentManager = new GoodsContentManager();
                $contentData    = [
                    'goods_id' => $goodId,
                    'type'     => $paid_content_type,
                    'content'  => $paid_content
                ];
                $contentManager->save($contentData);

                // 处理 spec
                $spec             = new GoodsSpecRelation();
                $spec->goods_id   = $goodId;
                $spec->spec_id    = 1;
                $spec->spec_value = [
                    'author' => $author
                ];
                $spec->create_at  = date('Y-m-d H:i:s');
                $spec->save();


                // 处理标签
                $goodId = $good->getData('id');
                if (!empty($tags)) {
                    $tagNames = explode(',', $tags);
                    $tagIds   = [];

                    foreach ($tagNames as $tagName) {
                        $tagName = trim($tagName);
                        if (empty($tagName))
                            continue;

                        // 查找或创建标签
                        $tag = GoodsTag::where('name', $tagName)->find();
                        if (!$tag) {
                            $tag = new GoodsTag();
                            $tag->save(['name' => $tagName]);
                            $tagIds[] = $tag->getData('id');
                        } else {
                            $tagIds[] = $tag->getData('id');
                        }
                    }

                    // 关联标签
                    if (!empty($tagIds)) {
                        foreach ($tagIds as $tagId) {
                            $relation = new GoodsTagRelation();
                            $relation->save([
                                'goods_id' => $goodId,
                                'tag_id'   => $tagId
                            ]);
                        }
                    }
                }

                // 提交事务
                Db::commit();

                // 获取商品ID
                $goodId = $good->getData('id');

                return json([
                    'code' => 1,
                    'msg'  => '发布成功',
                    'data' => [
                        'id'   => $goodId,
                        'name' => $name,
                        'url'  => '/item-' . $goodId
                    ]
                ]);

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->logger->error('火车头发布商品失败', ['error' => $e->getMessage()]);
                return json(['code' => 0, 'msg' => '发布失败: ' . $e->getMessage()]);
            }

        } catch (\Exception $e) {
            $this->logger->error('火车头发布接口异常', ['error' => $e->getMessage()]);
            return json(['code' => 0, 'msg' => '系统错误: ' . $e->getMessage()]);
        }
    }

    /**
     * 获取分类列表接口
     * @param Request $request
     * @return Response
     */
    public function categories(Request $request)
    {
        try {
            // 验证API密钥
            $api_key = $request->get('api_key', '');
            if ($api_key !== $this->getApiKey()) {
                return json(['code' => 0, 'msg' => 'API密钥错误']);
            }

            // 获取所有分类
            $categories = GoodsCategory::field('id, name, pid')
                ->order('sort desc, id asc')
                ->select()
                ->toArray();

            return json(['code' => 1, 'msg' => '获取成功', 'data' => $categories]);
        } catch (\Exception $e) {
            $this->logger->error('获取分类列表失败', ['error' => $e->getMessage()]);
            return json(['code' => 0, 'msg' => '获取分类列表失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 获取标签列表接口
     * @param Request $request
     * @return Response
     */
    public function tags(Request $request)
    {
        try {
            // 验证API密钥
            $api_key = $request->get('api_key', '');
            if ($api_key !== $this->getApiKey()) {
                return json(['code' => 0, 'msg' => 'API密钥错误']);
            }

            // 获取所有标签
            $tags = GoodsTag::field('id, name')
                ->order('id desc')
                ->select()
                ->toArray();

            return json(['code' => 1, 'msg' => '获取成功', 'data' => $tags]);
        } catch (\Exception $e) {
            $this->logger->error('获取标签列表失败', ['error' => $e->getMessage()]);
            return json(['code' => 0, 'msg' => '获取标签列表失败: ' . $e->getMessage()]);
        }
    }

    /**
     * 测试接口连通性
     * @param Request $request
     * @return Response
     */
    public function test(Request $request)
    {
        try {
            // 验证API密钥
            $api_key = $request->get('api_key', '');
            if ($api_key !== $this->getApiKey()) {
                return json(['code' => 0, 'msg' => 'API密钥错误']);
            }

            // 返回接口说明
            $api_info = [
                'publish'    => [
                    'url'    => '/api/huoche_publish/publish',
                    'method' => 'POST',
                    'params' => [
                        'api_key'              => '必填，API密钥',
                        'name'                 => '必填，商品名称',
                        'category_name'        => '选填，分类名称（与cate_id二选一）',
                        'cate_id'              => '选填，分类ID（与category_name二选一）',
                        'auto_create_category' => '选填，布尔值，是否自动创建不存在的分类，默认false',
                        'price'                => '选填，商品价格，默认0',
                        'cost_price'           => '选填，成本价，默认0',
                        'content'              => '必填，商品详情',
                        'paid_content'         => '选填，付费内容',
                        'paid_content_type'    => '选填，付费内容类型，默认text',
                        'tags'                 => '选填，标签，多个用逗号分隔',
                        'sort'                 => '选填，排序，默认自动计算',
                        'status'               => '选填，状态，1上架，0下架，默认1',
                        'seo_title'            => '选填，SEO标题',
                        'seo_keywords'         => '选填，SEO关键词',
                        'seo_description'      => '选填，SEO描述',
                        'template'             => '选填，模板',
                        'images'               => '选填，图片文件，可多个'
                    ]
                ],
                'categories' => [
                    'url'    => '/api/huoche_publish/categories',
                    'method' => 'GET',
                    'params' => ['api_key' => 'API密钥']
                ],
                'tags'       => [
                    'url'    => '/api/huoche_publish/tags',
                    'method' => 'GET',
                    'params' => ['api_key' => 'API密钥']
                ]
            ];

            $this->logger->info('火车头接口测试成功');
            return json([
                'code'     => 1,
                'msg'      => '接口连接成功',
                'time'     => date('Y-m-d H:i:s'),
                'api_info' => $api_info
            ]);
        } catch (\Exception $e) {
            $this->logger->error('火车头接口测试失败', ['error' => $e->getMessage()]);
            return json(['code' => 0, 'msg' => '接口异常: ' . $e->getMessage()]);
        }
    }
}